package com.sctvcloud.zhaohua_sd.ui.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.weather.LocalWeatherForecastResult;
import com.amap.api.services.weather.LocalWeatherLive;
import com.amap.api.services.weather.LocalWeatherLiveResult;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearchQuery;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.sctvcloud.zhaohua_sd.R;
import com.sctvcloud.zhaohua_sd.application.Cache;
import com.sctvcloud.zhaohua_sd.base.BaseFragment;
import com.sctvcloud.zhaohua_sd.beans.CityServiceBean;
import com.sctvcloud.zhaohua_sd.beans.FRebellion;
import com.sctvcloud.zhaohua_sd.beans.FocusColumn;
import com.sctvcloud.zhaohua_sd.beans.HomeEvent;
import com.sctvcloud.zhaohua_sd.beans.JSBeans;
import com.sctvcloud.zhaohua_sd.beans.MallJsonVo;
import com.sctvcloud.zhaohua_sd.beans.ServiceBean;
import com.sctvcloud.zhaohua_sd.beans.ServiceCityListVo;
import com.sctvcloud.zhaohua_sd.beans.ServiceConfigBean;
import com.sctvcloud.zhaohua_sd.beans.ServiceDataBean;
import com.sctvcloud.zhaohua_sd.beans.ServiceVo;
import com.sctvcloud.zhaohua_sd.beans.UserInfoBean;
import com.sctvcloud.zhaohua_sd.http.AbsListNetCallback;
import com.sctvcloud.zhaohua_sd.http.AbsNetCallBack;
import com.sctvcloud.zhaohua_sd.http.NetUtils;
import com.sctvcloud.zhaohua_sd.ui.activities.FoodCortsActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.H5NormalActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.JobActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.LoginActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.MyMainActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.NewH5Activity;
import com.sctvcloud.zhaohua_sd.ui.adapter.ServicePagerAdapter;
import com.sctvcloud.zhaohua_sd.ui.adapter.ServiceRecentlyUsedServiceAdapter;
import com.sctvcloud.zhaohua_sd.utils.GaoDeLocationUtil;
import com.sctvcloud.zhaohua_sd.utils.UserManager;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

public class ServiceFragment extends BaseFragment implements OnTabSelectListener, WeatherSearch.OnWeatherSearchListener, GaoDeLocationUtil.LocationChangeListener,
        ServiceRecentlyUsedServiceAdapter.OnServiceItemClickListener, ServiceColumnFragment.OnServiceUsedListener {
    private static final int TO_EXCHANGE_CITY = 1;
    private static final int CODE_REQUEST_LOGIN = 2;
    //    private String serviceUrl = "";
//    public static final String configUrl = "/sctv/appConfig.json";
//    private String cityUrl;
    private static final String RECENTLY_USED_SERVICE = "recently_used_service";

    @BindView(R.id.weather_num)
    protected CustomFontTextView weahterTemperature;
    @BindView(R.id.weather)
    protected CustomFontTextView weather;
    @BindView(R.id.wind_direction)
    protected CustomFontTextView windDirection;
    @BindView(R.id.wind_power)
    protected CustomFontTextView windPower;
    @BindView(R.id.humidity_tip)
    protected CustomFontTextView humidityTip;
    @BindView(R.id.humidity)
    protected CustomFontTextView humidity;
    @BindView(R.id.local_address)
    protected CustomFontTextView localAddress;


    @BindView(R.id.recently_used_layout)
    protected LinearLayout recentlyLayout;
    @BindView(R.id.recently_used_list)
    protected RecyclerView recentlyList;

    @BindView(R.id.service_tablay)
    protected SlidingTabLayout serviceTab;
    @BindView(R.id.service_content_vp)
    protected ViewPager serviceContentVp;

    private ServicePagerAdapter pagerAdapter;

    private ServiceRecentlyUsedServiceAdapter recentlyAdapter;

    private WeatherSearchQuery mquery = null;
    private WeatherSearch mweathersearch = null;
    private static final long TIME_LONG = 60 * 60 * 1000;//获取天气的时间间隔
    private long lastWeatherTime = 0;//最近一次获取天气信息

    private AMapLocation location;
    private List<ServiceBean> localServiceList;
    private List<ServiceDataBean> recentlyUsedServices;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_service, container, false);
        ButterKnife.bind(this, view);
        Cache.getInstance().setCurrentChannelId("");
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        isCoverStatusColor = false;
        super.onActivityCreated(savedInstanceState);
        StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.status_color));
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initRecentlyView();
        requestLocation();
        requestService();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            Cache.getInstance().setCurrentChannelId("");
            requestLocation();
            requestService();
            StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.status_color));
        }

    }

    private void initRecentlyView() {
        recentlyUsedServices = new ArrayList<>();
        List<ServiceDataBean> list = getRecentlyUsedService();
        if (ListUtils.isListValued(list)) {
            recentlyUsedServices.addAll(list);
        }
        GridLayoutManager mgr = new GridLayoutManager(getContext(), 4);
        recentlyList.setLayoutManager(mgr);
//        recentlyList.setItemAnimator(new DefaultItemAnimator());
        recentlyAdapter = new ServiceRecentlyUsedServiceAdapter();
        recentlyAdapter.setServiceItemClickListener(this);
        recentlyList.setAdapter(recentlyAdapter);
        refreshRecentLyService();
    }

    /**
     * 刷新最近使用的服务list
     */
    private void refreshRecentLyService() {
        List<ServiceDataBean> list = getRecentlyUsedService();
        if (ListUtils.isListValued(list)) {
            recentlyLayout.setVisibility(View.VISIBLE);
            recentlyAdapter.setData(list);
        } else {
            recentlyLayout.setVisibility(View.GONE);
        }

    }

    /**
     * 调用高德定位
     */
    private void requestLocation() {
        long time = System.currentTimeMillis() - lastWeatherTime;
        if (time >= TIME_LONG) {
            requestLocationCount = 0;
            location = null;
            GaoDeLocationUtil.getInstance().registerOnLocatedListener(this);
            GaoDeLocationUtil.getInstance().startLocate(getContext());
        }
    }

    private int requestLocationCount = 0;

    @Override
    public void onLocationChange(AMapLocation aMapLocation) {
        GaoDeLocationUtil.getInstance().unregisterOnLocatedListener(this);
        GaoDeLocationUtil.getInstance().stopLocate();
        requestLocationCount++;
        if (null != aMapLocation && !TextUtils.isEmpty(aMapLocation.getProvince())) {
            location = aMapLocation;
            String location = aMapLocation.getCity() + aMapLocation.getDistrict();
            requestWeather(aMapLocation.getDistrict());
            localAddress.setText(location);
        } else {
            if (requestLocationCount < 3) {//如果失败就再次定位，超过3次就不再继续
                GaoDeLocationUtil.getInstance().registerOnLocatedListener(this);
                GaoDeLocationUtil.getInstance().startLocate(getContext());
            } else {
                if (null != location) {
                    String mLocation = location.getCity() + location.getDistrict();
                    requestWeather(location.getDistrict());
                    localAddress.setText(mLocation);
                } else {
                    requestWeather("广元昭化区");
                    localAddress.setText("四川省广元市昭化区");
                }
            }
        }
    }


    /**
     * 高德地图获取天气数据
     *
     * @param localtion
     */
    private void requestWeather(String localtion) {
        //检索参数为城市和天气类型，实况天气为WEATHER_TYPE_LIVE、天气预报为WEATHER_TYPE_FORECAST
        mquery = new WeatherSearchQuery(localtion, WeatherSearchQuery.WEATHER_TYPE_LIVE);
        mweathersearch = new WeatherSearch(getContext());
        mweathersearch.setOnWeatherSearchListener(this);
        mweathersearch.setQuery(mquery);
        mweathersearch.searchWeatherAsyn(); //异步搜索

    }

    @Override
    public void onWeatherLiveSearched(LocalWeatherLiveResult weatherLiveResult, int rCode) {
        if (rCode == 1000) {
            if (weatherLiveResult != null && weatherLiveResult.getLiveResult() != null) {
                lastWeatherTime = System.currentTimeMillis();
                LocalWeatherLive weatherlive = weatherLiveResult.getLiveResult();
                if (!TextUtils.isEmpty(weatherlive.getWeather())) {
//                reporttime1.setText(weatherlive.getReportTime()+"发布");
                    weather.setText(weatherlive.getWeather());
                    weahterTemperature.setText(weatherlive.getTemperature());
                    windDirection.setText(weatherlive.getWindDirection() + "风");
                    windPower.setText(weatherlive.getWindPower() + "级");
                    humidityTip.setText("湿度");
                    humidity.setText(weatherlive.getHumidity() + "%");
                }
            } else {
                Toast.makeText(getContext(), "未获取到天气", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(getContext(), "未获取到天气", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onWeatherForecastSearched(LocalWeatherForecastResult localWeatherForecastResult, int i) {

    }

    /**
     * 获取服务数据
     */
    private void requestService() {
//        if(null==localServiceList) {
        ArrayMap<String, Object> map = new ArrayMap<>();
        map.put("1", "1");
        NetUtils.getNetAdapter().getServiceData(getOwnerName(), map, new AbsNetCallBack<ServiceVo>(ServiceVo.class) {
            @Override
            public void onSuc(ServiceVo serviceVo) {
                if (null != serviceVo.getServiceList()) {
                    localServiceList = serviceVo.getServiceList();
                    initServicePager(serviceVo.getServiceList());
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }
        });
//        }
    }

    private void initServicePager(List<ServiceBean> list) {
        if (pagerAdapter == null) {
            pagerAdapter = new ServicePagerAdapter(getChildFragmentManager(), list, this);
//            setAdapterTopHeiht(true);
            serviceContentVp.setAdapter(pagerAdapter);
            serviceContentVp.setOffscreenPageLimit(1);
            serviceTab.setViewPager(serviceContentVp);
//            pagerAdapter.notifyDataSetChanged();
        } else {
//            setAdapterTopHeiht(true);
            pagerAdapter.setServiceTypeList(list);
        }
        serviceTab.setOnTabSelectListener(this);
        refreshColumnTab();
    }

    @Override
    public void onServiceItemClick(ServiceDataBean item) {
        //最近使用的列表点击
        if ((null != item) && (null != item.getChannelType()) && item.getChannelType().equals("15")) {
            toFoodCort(item);
        } else {
            if(null != item&&item.getCommName().equalsIgnoreCase("昭化就业")){
//                if (getActivity()!= null && getActivity() instanceof MyMainActivity) {
//                    ((MyMainActivity)getActivity()).onTabChanged(2);
//                }
                if(Cache.getInstance().getJobId()!=0){
                    toJob(item);
//                    EventBus.getDefault().post(new HomeEvent(Cache.getInstance().getJobId()));
                }
            }else {
                toH5(item);
            }

        }
    }

    @Override
    public void onUsedService(ServiceDataBean item) {
        //服务列表中点击的回调
        if ((null != item) && (null != item.getChannelType()) && item.getChannelType().equals("15")) {
            toFoodCort(item);
        } else {
            if(null != item&&item.getCommName().equalsIgnoreCase("昭化就业")){
//                if (getActivity()!= null && getActivity() instanceof MyMainActivity) {
//                    ((MyMainActivity)getActivity()).onTabChanged(2);
//                }
                toJob(item);
            }else {
                toH5(item);
            }
        }
        saveRecentlyUsedService(item);
    }

    private void toFoodCort(ServiceDataBean item) {
        Intent intent = new Intent(getContext(), FoodCortsActivity.class);
        intent.putExtra(EX_TITLE, item.getCommName());
        intent.putExtra(EX_URL, item.getCommH5Url());
        startActivity(intent);

    }
    private void toJob(ServiceDataBean item) {
        Intent intent = new Intent(getContext(), JobActivity.class);
        intent.putExtra(EX_TITLE, item.getCommName());
        startActivity(intent);

    }
    private void toH5(ServiceDataBean item) {
        if (item.getCommH5Url().equalsIgnoreCase("http://file.scwy.tv/logo/page.html")) {
            if (UserManager.isLoginS()) {
                Intent intent = new Intent(getContext(), NewH5Activity.class);
                intent.putExtra(EX_TITLE, item.getCommName());
                intent.putExtra(EX_HTML, item.getCommH5Url());
                intent.putExtra(H5NormalActivity.IS_SHOW_TITTLE, true);
                startActivity(intent);
            } else {
                toLogin();
            }
        } else {
            Intent intent = new Intent(getContext(), H5NormalActivity.class);
            intent.putExtra(EX_TITLE, item.getCommName());
            intent.putExtra(EX_HTML, item.getCommH5Url());
            intent.putExtra(H5NormalActivity.IS_SHOW_TITTLE, true);
            startActivity(intent);
        }
    }

    @Override
    public void onTabSelect(int position) {

    }

    @Override
    public void onTabReselect(int position) {

    }

    @Override
    public void onTabScrollTo(int position) {

    }

    /**
     * 刷新栏目在首页的标签
     */
    private void refreshColumnTab() {
        int size = pagerAdapter.getCount();
        if (size == 0) {
            return;
        }
//        serviceTab.setTabSpaceEqual(false);
        float d = getResources().getDimension(R.dimen.tab_home_padding_m);
        if (size <= 6) {
            d = getResources().getDimension(R.dimen.tab_home_padding_l);
        } else if (size == 7) {
            d = getResources().getDimension(R.dimen.tab_home_padding);
        }
        serviceTab.setTabPaddingPx(d);
        serviceTab.notifyDataSetChanged();
//        }
    }

    @Override
    public void onDestroyView() {
        GaoDeLocationUtil.getInstance().stopLocate();
        super.onDestroyView();
    }


    protected void toLogin() {
        Intent intent = new Intent(getContext(), LoginActivity.class);
        startActivityForResult(intent, CODE_REQUEST_LOGIN);
    }


    /**
     * 获取当前保存的“最近使用的服务”
     *
     * @return
     */
    private List<ServiceDataBean> getRecentlyUsedService() {
        String str = (String) SharedPreferencesUtil.getParam(getContext(), RECENTLY_USED_SERVICE, "0000");
        if (!TextUtils.isEmpty(str) && !"0000".equalsIgnoreCase(str)) {
            Gson g = new Gson();
            List<ServiceDataBean> list = g.fromJson(str, new TypeToken<List<ServiceDataBean>>() {
            }.getType());
            return list;
        } else {
            return null;
        }
    }

    /**
     * 保存最新使用的服务
     *
     * @param service
     */
    private void saveRecentlyUsedService(ServiceDataBean service) {
        if (null != recentlyUsedServices && null != service) {
            for (int i = 0; i < recentlyUsedServices.size(); i++) {
                if (service.getCommName().equalsIgnoreCase(recentlyUsedServices.get(i).getCommName())) {
                    recentlyUsedServices.remove(i);
                    break;
                }
            }
            if (recentlyUsedServices.size() >= 4) {
                recentlyUsedServices.remove(0);
            }
            recentlyUsedServices.add(service);
            Gson g = new Gson();
            String jsonString = g.toJson(recentlyUsedServices);
            SharedPreferencesUtil.setParam(getContext(), RECENTLY_USED_SERVICE, jsonString);
            refreshRecentLyService();
        }
    }

//    @OnClick({R.id.title_top_address})
//    public void click(View view) {
//        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
//        pairs.add(new Pair<>("页面", "服务"));
//        switch (view.getId()) {
//            case R.id.title_top_address:
//                pairs.add(new Pair<>("行为类型", "点击"));
//                GridsumWebDissector.getInstance().trackEvent(this, "", "切换城市", "", 200, pairs);
//                Intent intent = new Intent(getContext(), ExchangeCityActivity.class);
//                startActivityForResult(intent, TO_EXCHANGE_CITY);
//                break;
//        }
//    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_REQUEST_LOGIN) {
            if (resultCode == LoginActivity.RESULT_OK) {

            }
        }
    }
}